package com.fundamentalesandroid;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.widget.TextView;

public class ExternalStorageTest extends Activity 	 {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		TextView textView=new TextView(this);
		setContentView(textView);
		String estado=Environment.getExternalStorageState();
		if(!estado.equals(Environment.MEDIA_MOUNTED)){
			textView.setText("No se ha montado la memoria externa");
		}else{
			File externalDir=Environment.getExternalStorageDirectory();
			File textFile=new File(externalDir.getAbsolutePath()+File.separator+"texto.txt");
			try {
				writeTextFile(textFile,"Prueba de almacenamiento externo");
				String texto=readTextFile(textFile);
				textView.setText(texto);
				if(!textFile.delete()){
					textView.setText("No se ha podido eliminar el archivo temporal");
				}
			}catch (IOException e){
				textView.setText("Se ha producido un error "+e.getMessage());
			}
		}
	}

	private void writeTextFile(File textFile,String string) throws IOException{
		BufferedWriter 	writer=new BufferedWriter(new FileWriter(textFile));
		writer.write(string);
		writer.close();
	}
	
	private String readTextFile(File textFile) throws IOException{
		BufferedReader reader=new BufferedReader(new FileReader(textFile));
		StringBuilder texto=new StringBuilder();
		String line;
		while((line=reader.readLine())!=null){
			texto.append(line);
			texto.append("\n");
		}
		reader.close();
		return texto.toString();
	}
	
}
